$(function() {

    let dog = new $.dog();

    let postId = $("#hidePostId").val();

    dog.get({
        url: '/api/v1/article/' + postId,
        success: function(result) {
            if (result.errCode != 0) {
                mdui.snackbar({
                    message: result.errDesc + "(" + result.errCode + ")",
                    timeout: 3000,
                    position: 'top',
                    onClose: function() {
                        window.location.href = "/";
                    }
                });
                return
            }
            let article = result.data
            refreshHtml(article);
        },
        error: function(error) {
            mdui.snackbar({
                message: error || '未找到文章',
                timeout: 3000,
                position: 'top',
                onClose: function() {
                    window.location.href = "/";
                }
            });
        }
    });

    /**
     * 填充内容
     * @param {*} article 
     */
    function refreshHtml(article) {
        let title = article.Title
        $('title').html(title);
        $("#articleTitle").html(title);
        $("#articleCover").html('<div class="PostTitleFill2 lazyload" data-bg="/' + article.Cover + '"> </div>');

        // 代码段格式化处理
        let content = article.Content.replace(/<pre><code class.*?\>/gi, '<pre>').replace(/<\/code><\/pre>/gi, "</pre>").replace(/<pre>/gi, '<pre class="EnlighterJSRAW">');
        $('.md_render').html(localPic(content));

        // 增加标签 html
        addTagHtml(article);

        // 增加用于截图的html
        addSharePicHtml(article);

        // 代码格式化
        EnlighterJS.init("pre.EnlighterJSRAW", 'code.EnlighterJSRAW', { "indent": 2, "ampersandCleanup": true, "linehover": false, "rawcodeDbclick": false, "textOverflow": "scroll", "linenumbers": true, "theme": "monokai", "language": "generic", "retainCssClasses": false, "collapse": false, "toolbarOuter": "", "toolbarTop": "", "toolbarBottom": "" });

        // 初始化目录(toc.js)
        initToc()
    }

    //  文章分享图处理
    function addSharePicHtml(article) {
        let shareHtml = ' <div class="mdx-si-head mdui-color-theme" style="background-image:linear-gradient(to bottom, rgba(0,0,0,0) 45%,rgba(0,0,0,0.7) 100%),url(' + article.Cover + ');"> <p>sszyc8</p><span>' + article.Title + '</span></div> <div class="mdx-si-sum">' + article.Introduction + '</div> <div class="mdx-si-box"><span>扫描二维码继续阅读</span><div class="mdx-si-qr" id="mdx-si-qr"></div> </div><div class="mdx-si-time">' + article.Time + '</div>';
        $('#mdx-share-img').html(shareHtml)

        new QRCode(document.getElementById("mdx-si-qr"), {
            text: window.location.href.split("?_pro=")[0].split("&_pro=")[0],
            width: 70,
            height: 70,
            correctLevel: QRCode.CorrectLevel.L,
            colorLight: '#f5f5f5'
        });

        var postTime = $('.mdx-si-time').html().split("-");
        $('.mdx-si-time').html(postTime[2] + '<br><span class="mdx-si-time-2">' + postTime[0] + '/' + postTime[1] + '</span>');
    }

    // 文章Tag处理
    function addTagHtml(article) {
        let tagHtml = '<i class="mdui-icon material-icons">&#xe54e;</i><span>'
        article.Tags.forEach(function(tag) {
            tagHtml = tagHtml + '<code>' + tag + '</code>  '
        })
        tagHtml = tagHtml + '</span><span class="mdui-text-color-black-disabled timeInPost" itemprop="datePublished"> <i class="mdui-icon material-icons info-icon">&#xe192;</i> ' + article.Time + ' </span>';
        $("#articleTag").html(tagHtml)
    }

    // 文章本地图地址处理
    function localPic(content) {
        return content.replaceAll('<img src="res/', '<img src="/res/')
    }
});

/**
 * 展示分享图
 */
function showSharePic() {
    window.share_dialog = mdui.dialog({
        content: '<div class="mdx-share-img-loaded" id="mdx-share-img-loaded-container"></div><div class="mdui-valign mdx-share-img-loading"><div class="mdui-center"><div class="mdui-spinner"></div></div></div>',
        buttons: [{ text: '关闭', }],
        history: false,
        cssClass: 'mdx-share-img-dialog'
    });
    mdui.updateSpinners();
    $('#mdx-share-img').show();

    if (!sessionStorage.getItem('si_' + window.location.href)) {
        html2canvas(document.getElementById("mdx-share-img"), { useCORS: true }).then(function(canvas) { convertCanvasToImage(canvas); });
    } else {
        var image = new Image();
        image.src = sessionStorage.getItem('si_' + window.location.href);
        document.getElementById('mdx-share-img-loaded-container').appendChild(image);
        $('#mdx-share-img').hide();
        $('div.mdx-share-img-loading').remove();
        setTimeout(() => {
            window.share_dialog.handleUpdate();
            $(".mdx-share-img-dialog .mdui-dialog-actions").prepend('<span class="mdx-save-info"><i class="mdui-icon material-icons">&#xe80d;</i> ' + '长按/右键保存图片' + '</span>');
        }, 5);
    }
}

/**
 * 生成分享图
 * @param {s} canvas 
 */
function convertCanvasToImage(canvas) {
    var image = new Image();
    var canvasData = canvas.toDataURL("image/png");
    sessionStorage.setItem('si_' + window.location.href, canvasData);
    image.src = canvasData;
    document.getElementById('mdx-share-img-loaded-container').appendChild(image);
    $('#mdx-share-img').hide();
    $('div.mdx-share-img-loading').remove();
    setTimeout(() => {
        window.share_dialog.handleUpdate();
        $(".mdx-share-img-dialog .mdui-dialog-actions").prepend('<span class="mdx-save-info"><i class="mdui-icon material-icons">&#xe80d;</i> ' + '长按/右键保存图片' + '</span>');
    }, 5);
}